package org.ch02.job.test11;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.Map;

import static org.ch02.job.test11.BuildFull.buildFullSql;

/**
 * @author XCH
 * @date 2025 - 03 - 19
 */
public class DbUtil {
    // 定义数据库连接URL
    private static final String URL = "jdbc:mysql://localhost:3306/stu?serverTimezone=UTC&useSSL=false&characterEncoding=utf8";


    // 定义数据库驱动类
    private static final String driver = "com.mysql.cj.jdbc.Driver";

    // 定义数据库用户
    private static final String username = "root";

    // 定义数据库密码
    private static final String password = "root";
    static {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("数据库驱动加载失败", e);
        }
    }

    public static int insert(User user) {
        String sql = SqlGenerate.generateInsert(User.class);
        try (Connection conn = DriverManager.getConnection(URL, username, password);
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            System.out.println("原始 SQL 语句：" + sql);

            Field[] fields = User.class.getDeclaredFields();
            int index = 1;
            for (Field field : fields) {
                field.setAccessible(true);
                Object value = field.get(user);
                stmt.setObject(index++, value);
            }

            String fullSql = buildFullSql(sql, user);
            System.out.println("完整 SQL 语句：" + fullSql);

            int rowsAffected = stmt.executeUpdate();
            System.out.println("插入操作影响的行数：" + rowsAffected);

            return rowsAffected;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
